console.log("loading: util.js");

function Util_Redirect(src){
	window.location.href = src;
}

function Util_HoldControl(selectorO){
	$(selectorO).addClass('control-hold');
}

function Util_UnHoldControl(selectorO){
	$(selectorO).removeClass('control-hold');
}

function Util_GetFontZoom(){
	var value = document.body.style.fontSize;
	if (value!=undefined){
		return value.match(/[0-9.]*/);
	}else{
		return 0.68;
	}
}

function Util_ImageCenter(imageElement){
	var $i = $(imageElement);
	$i.css({'margin-top':-$i.height()/2,'margin-left':-$i.width()/2});
}

function Util_FontZoomShowHide(ev,elem){
	var $elem = $(elem);
	if (Util_isLock($elem)){
		return;
	}
	new ZoomWidget().init({
		place:placeService.createPlace(OverlayPlace,{element:elem}),
		$contorlElement:$elem
	});
}

function Util_FontZoom(value){
	document.body.style.fontSize=0.75+0.06*value+'em';
}

function Util_FontZoomPos(value){
	Util_FontZoom(value);
	function onresult(json){
		if (Error.isError(json)) {
			console.error(Error.getErrorMessages(json));
			return;
		}
	}
	msgBroker.sendMessage(Messages.Preferences.zoomChanged(value), onresult);
}

function Util_FixBrokenImage(img,imgSrc){
	$(img).attr('src',imgSrc);
}

function Util_IsHoldControl(selectorO){
	return $(selectorO).hasClass('control-hold');
}

function ExecPostponed(condition, delegate, caller, args){
	var timer;
	if (condition.call(caller)){
		delegate.apply(caller, args);
	} else {
		timer = setInterval(function(){
			if (condition.call(caller)){
				clearInterval(timer);
				delegate.apply(caller, args);
			}
		}, 500);
	}
}

function Util_GetAbsolutePosition(selector){
	var $o = $(selector);
	var coord = {left:0,top:0};
	while ($o.length != 0){
		var of = $o.offset();
		coord.left += of.left;
		coord.top += of.top;
		$o = $o.parent();
	}
	return coord;
}

function LockUnlockScroll(isLock){
	var $body = $(document.body);
	var $notyBar = $('#noti-bar');
	isLock = (isLock==undefined? $body.css('overflow-y')!="hidden":isLock);
	if (!isLock){
		$body.css({'overflow-y':'scroll','width':'100%'});
		$notyBar.css('width',"100%");
	}else{
		$body.css({'overflow':'hidden','width':$body.width()});
		$notyBar.css('width',$body.width());
	}
}

function Util_AddClass(el,e,fclass){
	$(el).addClass(fclass);
}

function Util_RemoveClass(el,e,fclass){
	$(el).removeClass(fclass);
}

function Util_Animate(element,params,time,event){
	$(element).stop().animate(params,time);
}

function Util_AnimateShow(element,params,time,event){
	$(element).stop().css("visibility","visible").animate(params,time);
}

function Util_AnimateHide(element,params,time,event){
	element = $(element);
	element.stop().animate(params,time,function(){element.css("visibility","hidden");});
}

function trim(s) {
    return s.replace(/^\s+|\s+$/g, '');
}

function Textarea_Expand(el,e,fclass){
	if (!Util_IsHoldControl(el)){
		$(el).addClass(fclass);
		
	}
}

function Textarea_Collapse(el,e,fclass){
	if (!Util_IsHoldControl(el)){
		$(el).removeClass(fclass);
		
	}
}

function Textarea_ExpandAnime(el,e,params,time, controls){
	var $element = $(el); 
	if (!Util_IsHoldControl($element) && !$element.hasClass('l-expand')){
		if (controls && $.isArray(controls)) {
			var len = controls.length;
			for (var i = 0; i < len; i++) {
				$(controls[i]).show();
			}
		}	
		$element.addClass('l-expand').animate(params,time,function(){$element.focus();});
		if ($element.val() == GetLocaleString('wall.write.on.wall')) {
			$element.val('');
		}
	};
}
function Textarea_CollapseAnime(el,e,params,time, controls){
	var $element = $(el); 
	if (!Util_IsHoldControl(el) && $element.hasClass('l-expand')){
		if (controls && $.isArray(controls)) {
			var len = controls.length;
			for (var i = 0; i < len; i++) {
				$(controls[i]).hide();
			}
		}	
		$element.removeClass('l-expand').animate(params,time);
		if ($element.val() == '') {
			$element.val(GetLocaleString('wall.write.on.wall'));
		}
	}
}

// Display BLOCK
function Util_ShowInD(element,selector,event){
	$(selector,element).show();
}

// Display NONE
function Util_HideInD(element,selector,event){
	$(selector,element).hide();
}

// visibility visible
function Util_ShowInV(element,selector,event){
	$(selector,element).css("visibility","visible");
}

// visibility NONE
function Util_HideInV(element,selector,event){
	$(selector,element).css("visibility","hidden");
}

function Util_ArrayToTemplates(items,templateName,list){
	if (list == undefined){
		var list = [];
	}
	if (items==undefined){
		return list;
	}
	for ( var i=0;i<items.length;i++) {
		list.push(TM_FillTemplateData(templateName, items[i]));
	}
	return list;
}

function Animate_ShowToolbar(el,toolbarSelector,time,e){
	$($(toolbarSelector,el).eq(0)).css("visibility","visible");
}
function Animate_HideToolbar(el,toolbarSelector,time,e)
{
	var $toolBar= $($(toolbarSelector,el).eq(0));
	$toolBar.css("visibility","hidden");
}

function Util_UpdateCAPTCHA(event,elementSel){
	var old = $(elementSel).attr('src');
	var i = old.indexOf('.jsp');
	if (i!= -1){
		$(elementSel).attr('src',old.substr(0,i)+".jsp?t="+new Date().valueOf());
	}
	
}

function Util_AutoReloadItem(imgElem,attrName,src, tmpSrc){
    $(imgElem).attr(attrName,tmpSrc).oneTime('10s',function(){
		$(imgElem).attr(attrName,src+"?t="+new Date().valueOf());
	});
}

var previewDigestCache={};

function Preview_Move(target,elSel,e){
	var x = e.pageX?e.pageX:e.clientX + document.documentElement.scrollLeft;
	var y = e.pageY?e.pageY:e.clientY + document.documentElement.scrollTop;

	$(elSel).css({'position':'absolute','left':x+10+'px','top':y+10+'px'});
}

function Preview_Hide(elSel,e,params){
	Animate_HideToolbar(document.body,elSel,300,e);
}

function Preview_Show_Standalone(target,elSel,e,params,template){
	var x = e.pageX?e.pageX:e.clientX + document.documentElement.scrollLeft;
	var y = e.pageY?e.pageY:e.clientY + document.documentElement.scrollTop;
	var $preview_list = $(elSel).css({'position':'absolute','left':x+10+'px','top':y+10+'px'}).empty();
	Animate_ShowToolbar(document.body,elSel,300,e);
	
	
	function onRender()
	{
		$preview_list.html(TM_FillTemplateData(template,params));
	}
	TM_GetTemplate(template,onRender);
}

function Preview_Show(target,elSel,e,params,template){
	var x = e.pageX?e.pageX:e.clientX + document.documentElement.scrollLeft;
	var y = e.pageY?e.pageY:e.clientY + document.documentElement.scrollTop;
	var $preview_list = $(elSel).css({'position':'absolute','left':x+10+'px','top':y+10+'px'}).empty().attr('uid',params);

	Animate_ShowToolbar(document.body,elSel,300,e);

	function onRenderPreview(json)
	{
		/* if error */
		if (Error.isError(json)) {
			console.error(Error.getErrorMessages(json));
			return;
		}else
		{
			previewDigestCache[params] = json;
		}
		function onRender()
		{
			$preview_list.html(TM_FillTemplateData(template,json.list[0]));
		}
		if ($preview_list.attr('uid')!=params){
			return;
		}
		if (json.cfg.count>0)
		{
			TM_GetTemplate(template,onRender);
		}else
		{
			$preview_list.empty();
		}
	}
	var tmp = previewDigestCache[params];
	if (tmp == undefined)
	{
		msgBroker.sendMessage(Messages.Friends.getPreview(params), onRenderPreview);		
	} else
	{
		onRenderPreview(tmp);
	}
}

function Util_Date(date){
	var tmpMonth = date.getMonth()+1;
	return  date.getDate()+"."+(tmpMonth < 10 ? ('0'+tmpMonth) : (tmpMonth))+"."+date.getFullYear();/* date.toLocaleDateString(); */
}

function Util_Time(date){
	if (!date.getHours) {date = new Date(date);}
	var tmpMin = date.getMinutes();
	return  date.getHours()+ ":" + (tmpMin < 10 ? ('0'+tmpMin) : (tmpMin));
}

function Util_DateTimeStr(datestamp){
	var timeSpan = new Date().valueOf() - datestamp;
	var future = false;
	if (timeSpan<0){
		timeSpan = -timeSpan;
		future = true;
	}
	var d_ago = (timeSpan / (1000 * 60 * 60 * 24)).toFixed(0);
	if (d_ago>100){
		 return new Date(datestamp).asString("dd.mm.yy");
	}
    var h_ago = ((timeSpan - d_ago * 1000 * 60 * 60 *24) / (1000 * 60 * 60)).toFixed(0);
    var m_ago = ((timeSpan - h_ago * 1000 * 60 * 60) / (1000 * 60)).toFixed(0);

    if (d_ago == 0) {
        if (h_ago == 0) {
            if (m_ago == 0) {
                return (future?GetLocaleString("settings.datetime.now_f"):GetLocaleString("settings.datetime.now")).replace('%s', m_ago);
            }
            return (future?GetLocaleString("settings.datetime.minutes_f"):GetLocaleString("settings.datetime.minutes")).replace('%s', m_ago);
        }
        return (future?GetLocaleString("settings.datetime.hours_f"):GetLocaleString("settings.datetime.hours")).replace('%s',h_ago);
    }else
    if (d_ago < 5) {
        return (future?GetLocaleString("settings.datetime.days_f"):GetLocaleString("settings.datetime.days")).replace('%s',d_ago);
    }else
    return new Date(datestamp).asString("dd.mm");
}

function Util_Lock(el) {
	$(el).attr('lock', '1');
}

function Util_Unlock(el) {
	$(el).attr('lock', '0');
}

function Util_isLock(el) {
	return $(el).attr('lock') == '1';
}

function Util_htmlEscape(s) {
	  return s.replace(/&/, "&amp;")
	  .replace(/</, "&lt;")
	          .replace(/>/, "&gt;")
	          .replace(/"/, "&quot;")
	          .replace(/'/, "&apos;");
}

function Util_prvAutoTextBlur(){
	if(this.value==''){ 
		this.value=$(this).attr('avalue');
	}
}
function Util_prvAutoTextFocus(){
	if(this.value==$(this).attr('avalue'))
		this.value='';
}
function Util_AutoText($element){
	$element.each(function(e){
		var $t = $(this);
		if ($t.val()==""){
			$t.val($t.attr('avalue'));
		}
	});
	$element.bind('blur',Util_prvAutoTextBlur).bind('focus',Util_prvAutoTextFocus);
}
function Util_AutoTextClearValue($e){
	var value = $e.val();
	return (value == $e.attr('avalue'))?"":value;
}

function Util_setFormJSON($container,params) {
	if (params == undefined) {
		return;
	}
	
	function fillForm(){
		var $e = $(this);
		var name = $e.attr('json_name');
		if (name == undefined){
			return;
		}
		var type = $e.attr('json_type');
		if (type=='array'){
			var ar = params[name];
			var v = $e.val();
			for(var i=0 ; i < ar.length;i++){
				if(v == ar[i]){
					$e.attr("checked","checked");
					return;
				}
			}
			$e.removeAttr("checked");
		}else{
			if ($e.attr('type')=="checkbox"){
				params[name]=='1'?$e.attr("checked","checked"):$e.removeAttr("checked");
			}else{
				$e.val(params[name]);
			}
		}
	}
	
	$('textarea',$container).each(fillForm);
	$('input[type=text]',$container).each(fillForm);
	$('input[type=checkbox]',$container).each(fillForm);
	$('select',$container).each(fillForm);
}

function Util_getFormJSON($container,params) {
		if (params == undefined) {
			params = {};
		}
		function addValue(name, value) {
			if (name != undefined) {
				params[name] = value;
			}
		}
		function addArray(name, value) {
			if (name != undefined) {
				if (params[name] == undefined) {
					params[name] = [];
				}
				params[name].push(value);
			}
		}

		$('textarea',$container).each(function() {
			var $e = $(this);
			if ($e.attr('json_type') == "array") {
				addArray($e.attr('json_name'), $e.val());
			} else {
				addValue($e.attr('json_name'), $e.val());
			}
		});

		$('input[type=text]',$container).each(function() {
			var $e = $(this);
			if ($e.attr('json_type') == "array") {
				addArray($e.attr('json_name'), $e.val());
			} else {
				addValue($e.attr('json_name'), $e.val());
			}
		});
		$('input[type=checkbox]',$container).each(function() {
			var $e = $(this);
			if ($e.attr('json_type') == "array") {
				if ($e.attr('checked')) {
					addArray($e.attr('json_name'), $e.val());
				}
			} else {
				addValue($e.attr('json_name'), $e.attr('checked')?1:0);
			}
		});

		$('select',$container).each(function() {
			var $e = $(this);
			if ($e.attr('json_type') == "array") {
				addArray($e.attr('json_name'), $e.val());
			} else {
				addValue($e.attr('json_name'), $e.val());
			}
		});
		return params;
	};